package com.song.util;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class FastDfsUtil {
    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * 上传文件
     * @param file
     * @return
     */
    public StorePath upload(MultipartFile file){
        try {
            return storageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        } catch (IOException e) {
            log.error("上传文件【%s】失败，异常信息：%s", file.getName(), e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 上传文件
     * @param inputStream
     * @param filename
     * @return
     */
    public StorePath upload(InputStream inputStream, String filename){
        try {
            return storageClient.uploadFile(inputStream, inputStream.available(), FilenameUtils.getExtension(filename), null);
        } catch (IOException e) {
            log.error("上传文件【%s】失败，异常信息：%s", filename, e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 下载文件
     * @param filePath
     * @return
     */
    public byte[] download(String filePath){
        Map<String, String> map = parseFilePath(filePath);
        if (map == null){
            return null;
        }
        DownloadByteArray array = new DownloadByteArray();
        byte[] bytes = null;
        try {
            bytes = storageClient.downloadFile(map.get("group"), map.get("path"), array);
        } catch (Exception e) {
            log.error("下载【%s】文件失败，错误信息：%s", filePath, e.getMessage());
        }
        return bytes;
    }

    /**
     * 删除文件
     * @param filePath
     */
    public void delete(String filePath) {
        Map<String, String> map = parseFilePath(filePath);
        if (map == null) {
            throw new RuntimeException(String.format("删除【%s】文件失败", filePath));
        }
        storageClient.deleteFile(map.get("group"), map.get("path"));
    }

    /**
     * 获取下载文件的输入流
     * @param filePath
     * @return
     */
    public InputStream getFileInputStream(String filePath) {
        byte[] result = download(filePath);
        InputStream input = null;
        try {
            input = new ByteArrayInputStream(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return input;
    }

    /**
     * 解析文件路径，获取group和path信息
     * @param filePath
     * @return
     */
    public Map<String, String> parseFilePath(String filePath){
        if (ObjectUtils.isEmpty(filePath)){
            log.error("fastdfs地址【%s】错误", filePath);
            return null;
        }
        int index = filePath.indexOf("http:");
        if (index != -1){
            try {
                URL url = new URL(filePath);
                filePath = url.getPath();
            } catch (MalformedURLException e) {
                log.error("fastdfs地址【%s】错误，错误信息：%s", filePath, e.getMessage());
                return null;
            }
        }
        if (filePath.startsWith("/")){
            filePath = filePath.substring(1);
        }
        if (!StringUtils.contains(filePath, "/")) {
            log.error("fastdfs地址【{}】参数错误", filePath);
            return null;
        }
        String group = filePath.substring(0, filePath.indexOf("/"));
        String path = filePath.substring(filePath.indexOf("/") + 1);
        Map<String, String> map = new HashMap<>();
        map.put("group", group);
        map.put("path", path);
        return map;
    }
}
